import * as React from 'react';
import { connect } from 'react-redux';
import { login, setFormData, getCaptcha } from './myAuthAction';


interface IProps {
  loginId: string;
  username: string;
  password: string;
  captcha: string;
  captchaURL: string;
  login: () => any;
  setFormData: (key: string, value: string) => any;
  getCaptcha: () => any;
}

class Login extends React.Component<IProps, any> {

  componentDidMount() {
    this.props.getCaptcha();
  }

  onSubmit = (e: React.SyntheticEvent<any>) => {
    e.preventDefault();
    this.props.login();
  }

  onChange = (e: React.SyntheticEvent<any>, key: string) => {
    this.props.setFormData(key, (e.target as any).value)
  }

  render() {
    const {
      loginId,
      username,
      password,
      captcha,
      captchaURL,
      login,
      setFormData
    } = this.props
    return (
      <div style={{ display: 'flex' }} >
        <form
          onSubmit={this.onSubmit}
          style={{ display: 'flex', flexDirection: 'column' }}
        >
          <label>
            商户编号
            <input
              type='text'
              value={loginId}
              onChange={e => this.onChange(e, 'loginId')}
            />
          </label>
          <label>
            用户名
            <input
              type='text'
              value={username}
              onChange={e => this.onChange(e, 'username')}
            />
          </label>
          <label>
            密码
            <input
              type='password'
              value={password}
              onChange={e => this.onChange(e, 'password')}
            />
          </label>
          <label>
            验证码
            <input
              type='text'
              value={captcha}
              onChange={e => this.onChange(e, 'captcha')}
            />
          </label>
          {captchaURL ? (
            <div>验证码图片链接{captchaURL}</div>
          ) : <div>获取验证码失败</div> }
          <input type='submit' value='登录' />
        </form>

        <h2>二维码</h2>
      </div>
    )
  }
}



const mapStateToProps = (state: any) => {
  const { loginId, username, password, captcha, captchaURL } = state.authReducer
  return {
    loginId,
    username,
    password,
    captcha,
    captchaURL,
  }
}

const mapDispatchToProps = (dispatch: any) => ({
  login: () => dispatch(login()),
  setFormData: (key: string, value: string) => dispatch(setFormData(key, value)),
  getCaptcha: () => dispatch(getCaptcha()),
})

export default connect(mapStateToProps, mapDispatchToProps)(Login)
